﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public static partial class user
    {
        public static dynamic getRanklist(int start, int limit)
        {
            var sql = new Sql.SqlDataContext();
            var total = sql.User.Count(row => !row.disabled);
            var result = (from u in sql.User
                          where !u.disabled
                          from us in sql.UserStatistics
                          where us.username == u.username
                          let problemAccept = sql.Solve.Count(so => so.username == u.username && so.accept > 0)
                          orderby problemAccept descending, us.submit, u.regTime
                          select new
                          {
                              rank = (from u2 in sql.User
                                      where !u2.disabled
                                      from us2 in sql.UserStatistics
                                      where us2.username == u2.username
                                      let pac2 = sql.Solve.Count(s2 => s2.username == u2.username && s2.accept > 0)
                                      where pac2 > problemAccept || pac2 == problemAccept && us2.submit < us.submit
                                      select u2).Count() + 1,
                              u.nickname,
                              u.username,
                              u.motto,
                              us.accept,
                              problemAccept,
                              us.submit
                          }).Skip(start).Take(limit);
            return new
            {
                success = true,
                total,
                result
            };
        }
    }
}
